package org.spring.springboot.service.impl;

import org.spring.springboot.dao.CategoryDao;
import org.spring.springboot.domain.Category;
import org.spring.springboot.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryDao dao;

    public List<Category> selectAll(String userid) {
        List<Category> list = dao.selectAll(userid);
        return this.setAsTreeStruct(list);
    }

    public Category selectOne(String id) {
        return dao.selectOne(id);
    }

    public void save(Category obj) {
        dao.save(obj);
    }

    public void update(String id, String name, String title) {
        dao.update(id, name, title);
    }

    public void delete(String id) {
        dao.delete(id);
    }

    private List<Category> setAsTreeStruct(List<Category> orinList) {
        List<Category> validList = new ArrayList<>();
        List<Category> tempList = new ArrayList<>();
        tempList.addAll(orinList);

        for (Category p : tempList) {
            String pid = p.getPid();
            for (Category tmp : tempList) {
                String tid = tmp.getId();
                int cmpRet = pid.compareTo(tid);
                if (cmpRet == 0) {
                    tmp.addChild(p);
                    break;
                }
            }
        }

        for (Category p : tempList) {
            String pid = p.getPid();
            int cmpRet = pid.compareTo("root");
            if (cmpRet == 0) {
                validList.add(p);
            }
        }

        return validList;
    }

	@Override
	public List<Category> selectByNameAndTitle(String name, String title) {
		// TODO Auto-generated method stub
		 List<Category> list = dao.selectByNameAndTitle(name, title);
	        return list;
	}

	@Override
	public List<Category> selectByPid(String pid) {
		// TODO Auto-generated method stub
		List<Category> list = dao.selectByPid(pid);
        return list;
	}
}
